<template>
    <el-dialog v-model="fromParam.modal" :title="params.Id ? '编辑管理员' : '新增管理员'" width="640" top="10vh" @close="CloseReset">
        <el-form ref="rulesForm" :model="params" label-position="top" :rules="rules">
            <el-form-item label="管理员角色:">
                <MySelect v-model="params.RoleList" multiple :options="fromParam.roleList.data" value="Value" label="Title">
                </MySelect>
            </el-form-item>
            <el-form-item label="管理员账号:" prop="Username">
                <el-input v-model="params.Username" placeholder="请输入6-12位英文和数字组合" clearable
                    :disabled="params.Id !== undefined"></el-input>
            </el-form-item>
            <template v-if="!params.Id">
                <el-form-item label="管理员密码" prop="Password">
                    <el-input v-model="params.Password" :type="!passwordVisiable ? 'password' : 'text'"
                        placeholder="6-18位英文字母，数字，或数字字母组合" clearable>
                        <template #suffix>
                            <el-icon class="material-icons pointer" @click="SwicthVisiable('Password')">
                                {{ passwordVisiable ? "visibility" : "visibility_off" }}
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="确认密码:" prop="CofPassword">
                    <el-input v-model="params.CofPassword" placeholder="请输入和上面相同的密码"
                        :type="!cofPasswordVisiable ? 'password' : 'text'" clearable>
                        <template #suffix>
                            <el-icon class="material-icons pointer" @click="SwicthVisiable('CofPassword')">
                                {{ cofPasswordVisiable ? "visibility" : "visibility_off" }}
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
            </template>
            <el-form-item label="账户状态:">
                <el-radio-group v-model="params.Enable">
                    <el-radio v-for="state in ENABLE_STATE" :label="state[0]">
                        {{ state[1] }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否超级管理员:">
                <el-radio-group v-model="params.IsSuperManager">
                    <el-radio v-for="state in IS_SUPER_MANAGER" :label="state[0]">
                        {{ state[1] }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="CloseReset">取消</el-button>
            <el-button type="primary" @click="UpdateOrCreate" :loading="loading">确定</el-button>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, ref, watch } from 'vue';
import { FormInstance, FormRules } from 'element-plus';
import { PermessionUser } from './Def';
import { UserApi } from '@/api/permession/user';
import { ENABLE_STATE, IS_SUPER_MANAGER } from "./ConfigData"
import { MySelect } from "@/components"
import MessageUti from "@/library/utils/MessageUti"

const props = defineProps<{
    fromParam: PermessionUser.EditingDialog,
    GetData: () => void
}>()

const ConfirmPasswordCheck = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('密码不能为空'))
    } else if (params.value.Password !== value) {
        callback(new Error('输入的密码与确认密码不匹配'))
    } else {
        callback()
    }
}

const rules = ref<FormRules<PermessionUser.ParamsState>>({
    Username: { required: true, message: '账号名称为必填项', trigger: 'blur' },
    Password: { required: true, message: '密码为必填项', trigger: 'blur' },
    CofPassword: { required: true, validator: ConfirmPasswordCheck, trigger: 'blur' }
})

const defaultParams = ref<PermessionUser.ParamsState>({
    Id: undefined,
    Username: "",
    Enable: true,
    IsSuperManager: false,
    RoleList: [],
    Password: "",
    CofPassword: "",
})

const params = ref({ ...defaultParams.value })
const rulesForm = ref<FormInstance>();
const loading = ref(false)
const passwordVisiable = ref(false)
const cofPasswordVisiable = ref(false)

watch(() => props.fromParam.row, (val) => {
    params.value = val
})

const SwicthVisiable = (element: string) => {
    if (element === 'Password') {
        passwordVisiable.value = passwordVisiable.value ? false : true
    }
    if (element === 'CofPassword') {
        cofPasswordVisiable.value = cofPasswordVisiable.value ? false : true
    }
}

const CloseReset = () => {
    if (!rulesForm.value) return
    props.fromParam.modal = false
    nextTick(() => {
        params.value = { ...defaultParams.value }
        rulesForm.value?.resetFields()
    })
}

const UpdateOrCreate = async () => {
    if (!rulesForm.value) return
    
    const valid = await rulesForm.value.validate(() => { })
    if (!valid) { return }

    loading.value = true
    const Api = params.value.Id ? UserApi.UpdateUser : UserApi.InsertUser

    try {
        await Api({ ...params.value })
        CloseReset()
        props.GetData()
        MessageUti.showSuccess(`${params.value.Id ? "修改" : "新增"}成功`)
    }
    catch (error) { }
    finally {
        loading.value = false
    }
}

</script>

<style scoped></style>